package com.feng.profile.realm;

import com.feng.common.enums.AlgorithmEnum;
import com.feng.common.util.MD5Util;
import com.feng.profile.model.entity.QSysUser;
import com.feng.profile.model.entity.SysUser;
import com.feng.profile.model.enums.StatusEnum;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Objects;

/**
 * @author Lee
 */
public class UserRealm extends AuthorizingRealm {

    private final Logger LOGGER = LoggerFactory.getLogger(UserRealm.class);

    @PersistenceContext
    private EntityManager em;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal = (String) authenticationToken.getPrincipal();
        String credentials = new String((char[])authenticationToken.getCredentials());
        QSysUser qSysUser = QSysUser.sysUser;
        SysUser sysUser = new JPAQueryFactory(em).select(qSysUser)
                .from(qSysUser)
                .where(qSysUser.userName.eq(principal))
                .fetchOne();
        if (Objects.isNull(sysUser)) {
            LOGGER.info("用户不存在");
            throw new UnknownAccountException("用户不存在");
        }
        if (!sysUser.getPassword().equals(MD5Util.toMd5(AlgorithmEnum.MD5,credentials,principal).toString())) {
            LOGGER.info("密码错误");
            throw new IncorrectCredentialsException("密码不正确");
        }
        if (sysUser.getStatus().equals(StatusEnum.D)) {
            LOGGER.info("用户被锁定");
            throw new LockedAccountException("用户被锁定");
        }
        ByteSource salt = ByteSource.Util.bytes(sysUser.getUserName());
        return new SimpleAuthenticationInfo(principal, sysUser.getPassword(), salt, getName());
    }
}
